import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:example/utils/common.dart';

/// 自定义组件基类
abstract class CustomWidget<T extends GetxController> extends StatelessWidget
    with CustomAction<T> {
  final T initController;

  CustomWidget(T defaultController, {Key? key, T? externalController})
      : initController = externalController ?? defaultController,
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return _defaultConfig(context, initController);
  }
}

/// 自定义组件基类
abstract class CustomState<S extends StatefulWidget, T extends GetxController>
    extends State<S> with CustomAction<T> {
  final T initController;

  CustomState(T defaultController, {Key? key, T? externalController})
      : initController = externalController ?? defaultController;

  @override
  Widget build(BuildContext context) {
    return _defaultConfig(context, initController);
  }
}

mixin CustomAction<T extends GetxController> {
  Widget _defaultConfig(BuildContext context, T initController) {
    return GetBuilder<T>(
      init: initController,
      global: false,
      builder: (controller) {
        return _tapHideSoftKeyboard(context, child: initView(context, controller));
      },
    );
  }

  Widget _tapHideSoftKeyboard(BuildContext context, {required Widget child}) {
    return GestureDetector(
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);
        if (!currentFocus.hasPrimaryFocus &&
            currentFocus.focusedChild != null) {
          hideKeyboard();
        }
      },
      child: child,
    );
  }

  Widget initView(BuildContext context, T controller);
}
